<?php

namespace app\admin\controller\user\card;

use app\common\controller\Backend;
use app\common\exception\UploadException;
use app\common\library\Upload;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\exception\DbException;
use think\response\Json;
use think\Session;

/**
 * 客户持卡明细
 *
 * @icon fa fa-circle-o
 */
class Detail extends Backend
{

    /**
     * Detail模型对象
     * @var \app\admin\model\user\card\Detail
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\card\Detail;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $list = Db::name('wanlshop_shop')->field(['id,shopname'])->select();
            $this->view->assign("list", $list);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        //当前管理员店铺id
        $_admin = Session::get('adminshop');

        $defaultWhere=[];
        //当前店铺id
        $shop_id = Session::get('shop');
        if($_admin==1 && $shop_id >1){
            $defaultWhere['shop_id']= $shop_id;
        }elseif($_admin !=1){
            $defaultWhere['shop_id']= $_admin;
        }

        $list = $this->model
            ->where($where)
            ->where($defaultWhere)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items(),'shop_id'=>$shop_id,'admin'=>$_admin];
        return json($result);
    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import(){
        //$file = $this->request->request('file');

        $attachment = null;
        //默认普通上传文件
        $upFile = $this->request->file('fileUpload');
        $shopId = $_POST['shop_id'];
        try {
            $upload = new Upload($upFile);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        $file = $attachment->url;
        //$file =$this->request->file('fileUpload');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }

        // 根据文件类型选择解析器
        if ($ext === 'csv') {
            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        // 加载文件
        $objPHPExcel = $reader->load($filePath);
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        // 读取表头
        $headers = [];
        $headers = ['id','name','mobile','shop','cardname','cardnumber','account','cardtype','cardstatus','cardopeningtime','openingshop','cardprice','periodvalidity','leftamount','leftgiftamount','leftsecondaryamount','leftsecondarytimes','leftsecondarygifttimes'];

        // 读取数据行
        $data = [];
        for ($row = 2; $row <= $highestRow; $row++) {
            $rowData = [];
            for ($col = 1; $col < count($headers)+1; $col++) {
                $cell = $sheet->getCellByColumnAndRow($col, $row);
                $rowData[$headers[$col-1]] = $cell->getValue();
            }
            $data[] = $rowData;
        }
        $res = true;

        if (count($data) > 0) {
            foreach ($data as $key => &$row) {
                $row['shop_id']=$shopId;
                unset($row['id']);
                // $exist = $this->model->where('mobile',$row['mobile'])->find();
                // if ($exist) {
                //     unset($data[$key]);
                // }
            }
        }

        if (count($data) > 0) {
            // 处理数据并插入数据库
            $res = $this->model->insertAll($data);
        }

        if (false === $res) {
            $this->error(__('No rows were inserted'));
        }

        $this->success(__('导入成功'), null, ['count' => count($data)]);
    }

}
